/* NOTES
    CAL IMPLEMENTAR EL SAVEFORMAT AL TANCAR LA FINESTRA. POTSER AL BOTO. 


 */

package xmarti.vacaxm.client.sequence;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.event.ListSelectionEvent;
import xmarti.vacaxm.action.ImplSequence;
import xmarti.vacaxm.beans.sequence.SequenceType;
import xmarti.vacaxm.beans.sequence.State;
import xmarti.vacaxm.beans.sequence.StateDefault;
import xmarti.vacaxm.exception.ExceptionHibernateVacaxm;
import xmarti.vacaxm.exception.ExceptionXML;
import xmarti.vacaxm.format.FormatJSplitPane;
import xmarti.vacaxm.format.FormatJTableAndJSplitPane;
import xmarti.vacaxm.utils.JTableXM;
import xmarti.vacaxm.utils.TDSLanguageUtils;
import xmarti.vacaxm.utils.TableModel;
import xmarti.vacaxm.utils.Utils;

/**
 *
 * @author xmarti
 */
public class JPSequencesType extends javax.swing.JPanel {    
    private JTableXM jTableSequenceType;
    private TableModel model;
    private ImplSequence aSequence;
    private List<SequenceType> sequencesType;
    private SequenceType sequenceType;
    private boolean insert;        
    private FormatJTableAndJSplitPane formatPanel;
    private boolean handleAction;
    public JPSequencesType() {
        initComponents();
        this.handleAction=true;
        this.jTableSequenceType= new JTableXM() {
            @Override
            public void handleSelectionEvent(ListSelectionEvent e) {
                selectionEvent(e);
            }
        };
        this.jScrollPaneTable.setViewportView(this.jTableSequenceType);
        this.aSequence=new ImplSequence();
        
        try {           
           this.jTableSequenceType.chargeModel(this.getModel());           
           this.formatPanel= new FormatJTableAndJSplitPane(this.jSplitPane,this.jTableSequenceType,SequenceType.class.toString());          
           this.enabledObjects(false);
           this.formatPanel.chargeFormat();
        } catch (ExceptionHibernateVacaxm ex) {
            //exception chargeModel
            Logger.getLogger(JDState.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExceptionXML ex) {
            //exception writeXML
            Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private TableModel getModel() throws ExceptionHibernateVacaxm{                                            
            this.sequencesType=(List<SequenceType>)this.aSequence.getSequencesType();
            String [] columns={TDSLanguageUtils.getMessage("jPanelSequenceType.JTable.name.caption"),
                               TDSLanguageUtils.getMessage("jPanelSequenceType.JTable.description.caption"),                          
                          };    
            Object[][] dades=null;
            if (this.sequencesType.size()==0){
                dades=new Object[1][columns.length];                          
                //dades[0][0]=new SequenceType();
                dades[0][0]="-";
                dades[0][1]="-";
              
                
            }
            else{
                dades=new Object[this.sequencesType.size()][columns.length];                          
                Integer i=0;            
                for (Iterator it = this.sequencesType.iterator(); it.hasNext();) {
                    SequenceType c = (SequenceType) it.next();                
                    //dades[i][0]= c;                                     
                    dades[i][0]= c.getName();                                     
                    if (c.getDescription()==(null))dades[i][1]="-"; else dades[i][1]= c.getDescription();                    
                    i++;
                }     
            }                  
        return new TableModel(columns, dades);   
   }
   private void chargeStatesAvailables() throws ExceptionHibernateVacaxm{
       DefaultListModel listModel= new DefaultListModel(); 
       listModel.removeAllElements();
       for(State state:this.aSequence.getStates()){
           if(!isAdded(state)) listModel.addElement(state);
       }
       this.jListAvailable.setModel(listModel);
   }
   private void chargeStatesAdded(){
      int id=-1; 
       DefaultListModel listModel= new DefaultListModel(); 
        if (this.jListAdded.getSelectedIndex() > -1) {
            StateDefault c =(StateDefault) this.jListAdded.getSelectedValue();
            id=c.getId();
        }        
        listModel.removeAllElements();
        for(StateDefault s:this.sequenceType.getStates()){            
            listModel.addElement(s);
        }
        this.jListAdded.setModel(listModel);
        this.jListAdded.setSelectedIndex(getIndexStatesAdded(id));                
   }
   private int getIndexStatesAdded(int id){
       for(int i=0; i< this.jListAdded.getModel().getSize();i++){
           StateDefault s=(StateDefault) this.jListAdded.getModel().getElementAt(i);
           if(s.getId() ==id)return i; 
       }
       return -1;
   }
   private boolean isAdded(State state){       
       for(int i =0; i<jListAdded.getModel().getSize();i++){
           StateDefault stateDefault=(StateDefault)jListAdded.getModel().getElementAt(i);
           if (stateDefault.getState().equals(state)) return true; 
       }       
       return false; 
   }
   private void enabledObjects(boolean modify){    
       this.jPanelStatesDefault.setVisible(modify);
       this.jButtonModify.setEnabled(modify);
       this.jButtonRemove.setEnabled(modify);       
       if(modify){                     
            if(this.jListAvailable.getSelectedIndex()>-1){
                this.jButtonIn.setEnabled(true);
            }else{
                this.jButtonIn.setEnabled(false);
            }           
            if(this.jListAdded.getSelectedIndex()>-1){
                this.jButtonOut.setEnabled(true);
            }else{
                this.jButtonOut.setEnabled(false);
            }
           if(this.jListAdded.getSelectedIndex()>-1&&this.jListAdded.getModel().getSize()>1){
                
                if(this.jListAdded.getSelectedIndex()==0){
                    this.jButtonUp.setEnabled(false);
                    this.jButtonDown.setEnabled(true);
                }else if(this.jListAdded.getSelectedIndex()==this.jListAdded.getModel().getSize()-1){ 
                    this.jButtonUp.setEnabled(true);
                    this.jButtonDown.setEnabled(false);
                }else{
                    this.jButtonUp.setEnabled(true);
                    this.jButtonDown.setEnabled(true);
                }               
            }else{
               
                this.jButtonUp.setEnabled(false);
                this.jButtonDown.setEnabled(false);
            }           
       }       
   }
   
   private void setData(){      
       chargeStatesAdded();
        try {
            chargeStatesAvailables();
        } catch (ExceptionHibernateVacaxm ex) {
            Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.jLabelAdded.setText(TDSLanguageUtils.getMessage("jPanelSequenceType.JLabel.added.caption")+sequenceType.toString() );
   }
        
    public void setFormat(){
        this.formatPanel.setFormat();
        try {
            this.formatPanel.saveFormat();
        } catch (ExceptionXML ex) {
            Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private int getSelectedIndex(){ // aqui esta el fallo
        int index=-1;         
        for(int i =0;i< jTableSequenceType.getRowCount();i++){
            if(jTableSequenceType.getValueAt(i, 0).toString().equals(this.sequenceType.toString())){ 
                return i;
            } 
        }
        return index; 
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane = new javax.swing.JSplitPane();
        jPanalSequenceType = new javax.swing.JPanel();
        jScrollPaneTable = new javax.swing.JScrollPane();
        jToolBar1 = new javax.swing.JToolBar();
        jButtonNew = new javax.swing.JButton();
        jButtonModify = new javax.swing.JButton();
        jButtonRemove = new javax.swing.JButton();
        jPanelStatesDefault = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListAdded = new javax.swing.JList();
        jLabelAdded = new javax.swing.JLabel();
        jButtonIn = new javax.swing.JButton();
        jButtonOut = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jListAvailable = new javax.swing.JList();
        jLabelAvailables = new javax.swing.JLabel();
        jButtonUp = new javax.swing.JButton();
        jButtonDown = new javax.swing.JButton();
        jButtonStates = new javax.swing.JButton();

        jSplitPane.setDividerLocation(200);
        jSplitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jToolBar1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jToolBar1.setFloatable(false);

        jButtonNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoNou.png"))); // NOI18N
        jButtonNew.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.new.toolTipText"));
        jButtonNew.setFocusable(false);
        jButtonNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonNew);

        jButtonModify.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoModificar.png"))); // NOI18N
        jButtonModify.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.modify.toolTipText"));
        jButtonModify.setFocusable(false);
        jButtonModify.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonModify.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonModify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModifyActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonModify);

        jButtonRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoBorrar.png"))); // NOI18N
        jButtonRemove.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.remove.toolTipText"));
        jButtonRemove.setFocusable(false);
        jButtonRemove.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonRemove.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoveActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonRemove);

        javax.swing.GroupLayout jPanalSequenceTypeLayout = new javax.swing.GroupLayout(jPanalSequenceType);
        jPanalSequenceType.setLayout(jPanalSequenceTypeLayout);
        jPanalSequenceTypeLayout.setHorizontalGroup(
            jPanalSequenceTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanalSequenceTypeLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanalSequenceTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPaneTable)
                    .addGroup(jPanalSequenceTypeLayout.createSequentialGroup()
                        .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
                        .addGap(514, 514, 514)))
                .addContainerGap())
        );
        jPanalSequenceTypeLayout.setVerticalGroup(
            jPanalSequenceTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanalSequenceTypeLayout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addComponent(jScrollPaneTable, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 15, Short.MAX_VALUE))
        );

        jSplitPane.setTopComponent(jPanalSequenceType);

        jPanelStatesDefault.setLayout(null);

        jListAdded.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jListAdded.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListAdded.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JList.added.toolTipText"));
        jListAdded.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListAddedValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(jListAdded);

        jPanelStatesDefault.add(jScrollPane2);
        jScrollPane2.setBounds(457, 45, 160, 138);

        jLabelAdded.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabelAdded.setText(TDSLanguageUtils.getMessage("jPanelSequenceType.Jlabel.added.caption"));
        jPanelStatesDefault.add(jLabelAdded);
        jLabelAdded.setBounds(457, 23, 160, 16);

        jButtonIn.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButtonIn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoFletxaDreta.png"))); // NOI18N
        jButtonIn.setText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.in.caption"));
        jButtonIn.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.in.toolTipText"));
        jButtonIn.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        jButtonIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInActionPerformed(evt);
            }
        });
        jPanelStatesDefault.add(jButtonIn);
        jButtonIn.setBounds(233, 57, 193, 45);

        jButtonOut.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButtonOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoFletxaEsquerra.png"))); // NOI18N
        jButtonOut.setText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.out.caption"));
        jButtonOut.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.out.toolTipText"));
        jButtonOut.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jButtonOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOutActionPerformed(evt);
            }
        });
        jPanelStatesDefault.add(jButtonOut);
        jButtonOut.setBounds(233, 113, 193, 46);

        jListAvailable.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jListAvailable.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListAvailable.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JList.availables.toolTipText"));
        jListAvailable.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListAvailableValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(jListAvailable);

        jPanelStatesDefault.add(jScrollPane3);
        jScrollPane3.setBounds(50, 46, 177, 137);

        jLabelAvailables.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabelAvailables.setText(TDSLanguageUtils.getMessage("jPanelSequenceType.JLabel.availables.caption"));
        jPanelStatesDefault.add(jLabelAvailables);
        jLabelAvailables.setBounds(50, 23, 240, 15);

        jButtonUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoFletxaDalt.png"))); // NOI18N
        jButtonUp.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.up.toolTipText"));
        jButtonUp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonUpActionPerformed(evt);
            }
        });
        jPanelStatesDefault.add(jButtonUp);
        jButtonUp.setBounds(623, 53, 37, 59);

        jButtonDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoFletxaBaix.png"))); // NOI18N
        jButtonDown.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.down.toolTipText"));
        jButtonDown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDownActionPerformed(evt);
            }
        });
        jPanelStatesDefault.add(jButtonDown);
        jButtonDown.setBounds(623, 118, 37, 59);

        jButtonStates.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButtonStates.setText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.states.caption"));
        jButtonStates.setToolTipText(TDSLanguageUtils.getMessage("jPanelSequenceType.JButton.states.toolTipText"));
        jButtonStates.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonStatesActionPerformed(evt);
            }
        });
        jPanelStatesDefault.add(jButtonStates);
        jButtonStates.setBounds(50, 186, 177, 39);

        jSplitPane.setRightComponent(jPanelStatesDefault);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInActionPerformed
        
            // cal obtenir el max del stateDefault per la sequencia tipus.
            // crear un nou StateDefault (int order,State state,SequenceType sequenceType)
            // guardar el StateDefault
            // fer un set StatesDefault del sequenceTypeActual
            // fer un setData
        if(this.jListAvailable.getSelectedIndex()>-1){                   
            State state= (State)this.jListAvailable.getSelectedValue();
            int max= aSequence.getMaxOrder(this.sequenceType);
            int maxId= this.aSequence.getMaxIdStateDefault(sequenceType);
            StateDefault stateDefault= new StateDefault(maxId+1, max+1,state,this.sequenceType);
            try {
                this.aSequence.add(stateDefault);        
                this.sequenceType=this.aSequence.getById(this.sequenceType.getId());           
                setData();
                this.jListAdded.setSelectedIndex(this.jListAdded.getMaxSelectionIndex());
                enabledObjects(true);
            } catch (ExceptionHibernateVacaxm ex) {
                Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButtonInActionPerformed

    private void jButtonOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOutActionPerformed
        
            // Cal borrar l'estatDefault
            // reordenar els statsDefault del sequenceTypeActual
            // fer un set statesDefault del sequenceTypeActual
            // fer un setData
        if(this.jListAdded.getSelectedIndex()>-1){                  
            this.aSequence.deleteStateDefault((StateDefault)this.jListAdded.getSelectedValue());                      
            try { 
                this.sequenceType.getStates().remove((StateDefault)this.jListAdded.getSelectedValue());
                this.sequenceType= this.aSequence.getById(this.sequenceType.getId());
                int i=1;
                for(StateDefault stateDefault:this.sequenceType.getStates()){
                    stateDefault.setOrder(i);
                    i++;
                }
                this.aSequence.update(this.sequenceType);                
                 setData();
                 enabledObjects(true); 
             } catch (ExceptionHibernateVacaxm ex) {
                 Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
             }
       }
    }//GEN-LAST:event_jButtonOutActionPerformed

    private void jButtonStatesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStatesActionPerformed
        final JDState dialog = new JDState();               
                dialog.setLocationRelativeTo(this);
                dialog.setVisible(true);
        try {                 
            chargeStatesAvailables();                
            enabledObjects(true); 
        }catch (ExceptionHibernateVacaxm ex) {
            Logger.getLogger(JDState.class.getName()).log(Level.SEVERE, null, ex);            
        }            
    }//GEN-LAST:event_jButtonStatesActionPerformed

    private void jButtonUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpActionPerformed
        
        // Cal intercanviar l'ordre entre l'estatDefaultActual amb el seu anterior
        // cal guardar els dos StateDefault. CAL ESTUDIAR COM FER-HO
        // cal fer un set StatesDefault del sequenceType Actual
        // cal fer un chargeAdded
        // cal tornar a seleccionar l'estatDefault actual (implementar-ho al chargeAdded)
        int i;
        StateDefault stateDefaultActive = (StateDefault)this.jListAdded.getSelectedValue();    
        
        this.sequenceType.changeOrder(stateDefaultActive, -1);
        
        try {                      
            this.aSequence.update(this.sequenceType);               
            selectionEvent(null);
            
        } catch (ExceptionHibernateVacaxm ex) {
            Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_jButtonUpActionPerformed

    private void jButtonDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDownActionPerformed
        // Cal intercanviar l'ordre entre l'estatDefaultActual amb el seu posterior
        // cal guardar els dos StateDefault. CAL ESTUDIAR COM FER-HO
        // cal fer un set StatesDefault del sequenceType Actual
        // cal fer un chargeAdded
        // cal tornar a seleccionar l'estatDefault actual (implementar-ho al chargeAdded)
        int i;
        StateDefault stateDefaultActive = (StateDefault)this.jListAdded.getSelectedValue();
        
        
        this.sequenceType.changeOrder(stateDefaultActive, 1);
       
        try {
            this.aSequence.update(this.sequenceType);               
            selectionEvent(null);       
        } catch (ExceptionHibernateVacaxm ex) {
            Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    }//GEN-LAST:event_jButtonDownActionPerformed

    private void jButtonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveActionPerformed
        if (Utils.confirmRemoveOptionPane(TDSLanguageUtils.getMessage("jPanelSequenceType.JOptionPane.remove.description")+ " "+ this.sequenceType +"?. ")==0){                              
            try {
               aSequence.remove(this.sequenceType);                
               this.handleAction=false;
               this.formatPanel.setFormat();               
                    this.jTableSequenceType.chargeModel(this.getModel());                               
               this.formatPanel.chargeFormat();
               this.handleAction=true;
               enabledObjects(false);  
               
            } catch (ExceptionHibernateVacaxm ex) {
                Logger.getLogger(JDState.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        
    }//GEN-LAST:event_jButtonRemoveActionPerformed

    private void jButtonNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewActionPerformed
        
            //cal cridar el JDSequenceType
            //després anotar el resultat a la taula.
            this.sequenceType= new SequenceType();
            JDSequenceType dialog = new JDSequenceType(null,true,this.sequenceType);
            dialog.setLocationRelativeTo(this);
            dialog.show();
            this.sequenceType=dialog.getSequenceType();           
        try {
            this.handleAction=false;
            this.formatPanel.setFormat(); 
                this.jTableSequenceType.chargeModel(this.getModel());            
                int i=getIndexSelected(this.sequenceType.getId());                        
                if(i >-1) {
                    this.jTableSequenceType.setRowSelectionInterval(i, i);
                    enabledObjects(true);                 
                }else{
                    enabledObjects(false);                 
                }
            this.formatPanel.chargeFormat();
            this.handleAction=true;
        } catch (ExceptionHibernateVacaxm ex) {
            Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_jButtonNewActionPerformed

    private void jListAddedValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListAddedValueChanged
        this.enabledObjects(true);                  
    }//GEN-LAST:event_jListAddedValueChanged

    private void jListAvailableValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListAvailableValueChanged
        this.enabledObjects(true);        
    }//GEN-LAST:event_jListAvailableValueChanged

    private void jButtonModifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModifyActionPerformed
        
        int i = this.sequenceType.getId();
        JDSequenceType dialog = new JDSequenceType(null,true,this.sequenceType);
        dialog.setLocationRelativeTo(this);
        dialog.show();
        try {
            this.handleAction=false;
            this.formatPanel.setFormat();           
                this.jTableSequenceType.chargeModel(this.getModel());              
                i=getIndexSelected(i);
                if(i >-1) this.jTableSequenceType.setRowSelectionInterval(i, i);
                this.enabledObjects(true);
            this.formatPanel.chargeFormat();
            this.handleAction=true;
        } catch (ExceptionHibernateVacaxm ex) {
            Logger.getLogger(JPSequencesType.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }//GEN-LAST:event_jButtonModifyActionPerformed
    private int getIndexSelected(int index){
        String name=null;
        for(SequenceType s: this.sequencesType){
            if(s.getId()==index) name=s.getName();
        }
        if (name!=null){
            for(int i =0; i<this.jTableSequenceType.getRowCount();i++){
                if(name.equals(this.jTableSequenceType.getValueAt(i, 0))) return i;
            }
        }   
        return -1 ;         
    }
    private void selectionEvent(ListSelectionEvent e){                    
        if(this.jTableSequenceType.getSelectedRow()>-1){                                  
           if(this.handleAction)    formatPanel.setFormat();
                this.sequenceType=this.aSequence.getSequenceTypeByName((String) this.jTableSequenceType.getValueAt(this.jTableSequenceType.getSelectedRow(),0)); 
                if (this.sequenceType.getId()==-1) {
                    this.insert=true;                                          
                    jButtonNewActionPerformed(null);                    
                } else{                    
                    this.insert=false;                     
                    setData();                
                    enabledObjects(true);   
                }                                               
           if(this.handleAction)    formatPanel.chargeFormat();
        }
     }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonDown;
    private javax.swing.JButton jButtonIn;
    private javax.swing.JButton jButtonModify;
    private javax.swing.JButton jButtonNew;
    private javax.swing.JButton jButtonOut;
    private javax.swing.JButton jButtonRemove;
    private javax.swing.JButton jButtonStates;
    private javax.swing.JButton jButtonUp;
    private javax.swing.JLabel jLabelAdded;
    private javax.swing.JLabel jLabelAvailables;
    private javax.swing.JList jListAdded;
    private javax.swing.JList jListAvailable;
    private javax.swing.JPanel jPanalSequenceType;
    private javax.swing.JPanel jPanelStatesDefault;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPaneTable;
    private javax.swing.JSplitPane jSplitPane;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables
}
